package com.amigo.online.provider.manager.util.video.processing;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import javax.annotation.Resource;

import org.jboss.logging.Logger;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import com.amigo.online.provider.manager.util.FastDFSClient;
import com.amigo.online.provider.manager.util.video.uploading.QiniuUtil;
import com.qiniu.http.Response;

@Component
public class FFMpegMusicUtil {

    private static final Logger logger = Logger.getLogger(FFMpegMusicUtil.class);
    private static String FFMPEG_PATH;// ffMpeg解压的bin地址
    private static String TMP_PATH;// 转为音频后 存放的地址
    private static String MUSIC_ADDRESS;
    private static String PICTURE_ADDRESS;
    @Resource
    QiniuUtil qiniuUtil;

    @Value("${ffmpeg_path}") // 获取配置文件的参数
    public void setFFMPEG_PATH(String fFMPEG_PATH) {
        FFMPEG_PATH = fFMPEG_PATH;
    }

    @Value("${tmp_path}")
    public void setTMP_PATH(String tMP_PATH) {
        TMP_PATH = tMP_PATH;
    }

    @Value("${music_address}")
    public void setMUSIC_ADDRESS(String mUSIC_ADDRESS) {
        MUSIC_ADDRESS = mUSIC_ADDRESS;
    }

    @Value("${picture_address}")
    public void setpICTURE_ADDRESS(String pICTURE_ADDRESS) {
        PICTURE_ADDRESS = pICTURE_ADDRESS;
    }


    /**
     * 视频转音频 返回上传的音频地址
     *
     * @param videoUrl视频地址
     */
    public String videoToAudio(String videoUrl, String videoName) {
        String musicUrl = "";
        try {
            String aacFile = TMP_PATH + videoName + ".mp3";
            String command = FFMPEG_PATH + "ffmpeg -i " + videoUrl + " -y -f mp3 -vn " + aacFile;
            logger.info("video to audio command : " + command);
            Process process = Runtime.getRuntime().exec(command);
            process.waitFor();
            // 上传七牛云
            Response res = qiniuUtil.uploadMusic(aacFile, videoName + ".mp3");
            if (res != null && res.isOK()) {
                // 上传的地址
                musicUrl = MUSIC_ADDRESS + videoName + ".mp3";
                // 上传成功后删除本地音频文件
                File file = new File(aacFile);
                file.delete();
            } else {
                logger.error("音频文件上传失败,音频路径：" + aacFile);
            }
        } catch (Exception e) {
            logger.error("音频提取失败，视频地址：" + videoUrl, e);
        }
        return musicUrl;
    }

    /**
     * 视频转音频上传服务器
     *
     * @param videoUrl
     * @param videoName
     * @return
     */

    public String videoToMusic(String videoUrl, String videoName) {
        String musicUrl = "";
        try {
            // 音频位置
            String aacFile = TMP_PATH + videoName + ".mp3";
            String command = FFMPEG_PATH + "ffmpeg -i " + videoUrl + " -y -f mp3 -vn " + aacFile;
            logger.info("video to audio command : " + command);
            Process process = Runtime.getRuntime().exec(command);
            process.waitFor();
            // 上传的地址
            // musicUrl = MUSIC_ADDRESS + videoName + ".mp3";
            File ff = new File(aacFile);

            FileInputStream fs = new FileInputStream(ff);
            byte[] bytes = new byte[fs.available()];
            // 将文件内容写入字节数组，提供测试的case
            fs.read(bytes);
            // 获取视频长传地址
            musicUrl = FastDFSClient.uploadFile(bytes, null);
            fs.close();
            // 上传成功后删除本地音频文件
            File file = new File(aacFile);
            file.delete();
            logger.info("上传后的音频地址:" + musicUrl);
        } catch (Exception e) {
            logger.error("音频提取失败，视频地址：" + videoUrl, e);
        }
        return musicUrl;

    }

    /****
     * 获取指定时间内的图片并上传到七牛云
     *
     * @param videoFilename:视频路径
     * @param thumbName:图片名称
     * @param thumbFilename:图片保存路径
     * @param width:图片宽
     * @param height:图片高
     * @param hour:指定时
     * @param min:指定分
     * @param sec:指定秒
     * @throws IOException
     * @throws InterruptedException
     */
    public String getThumb(String videoFilename, String thumbName, int width, int height, int hour, int min, float sec)
            throws IOException, InterruptedException {
        String pictureUrl = "";
        String thumbFilename = TMP_PATH + thumbName + ".jpg";
        logger.info("图片存放地址" + thumbFilename);
        // String command =FFMPEG_PATH+" -y -i "+videoFilename+"vframes 1"+" -ss"+hour +
        // ":" + min + ":" + sec+"-f mjpeg -s"+width+"*"+ height+" -an"+thumbFilename;
        ProcessBuilder processBuilder = new ProcessBuilder(FFMPEG_PATH + "ffmpeg.exe", "-y", "-i", videoFilename,
                "-vframes", "1", "-ss", hour + ":" + min + ":" + sec, "-f", "mjpeg", "-s", width + "*" + height, "-an",
                thumbFilename);
        logger.info("processBuilder======" + processBuilder);
        Process process = processBuilder.start();
        InputStream stderr = process.getErrorStream();
        InputStreamReader isr = new InputStreamReader(stderr);
        BufferedReader br = new BufferedReader(isr);
        @SuppressWarnings("unused")
        String line;
        while ((line = br.readLine()) != null)
            ;
        process.waitFor();
        if (br != null)
            br.close();
        if (isr != null)
            isr.close();
        if (stderr != null)
            stderr.close();

        logger.info("图片名称" + thumbName);
        // 上传七牛云
        Response res = qiniuUtil.uploadPicture(thumbFilename, thumbName);
        if (res != null && res.isOK()) {
            // 上传的地址
            pictureUrl = PICTURE_ADDRESS + thumbName;
            // 上传成功后删除本地图片
            File file = new File(thumbFilename);
            file.delete();
        } else {
            logger.error("图片文件上传失败,图片路径：" + thumbFilename);
        }
        return pictureUrl;
    }

    /**
     * 获取视频第一帧并上传到服务器
     *
     * @param videoFilename:视频路径
     * @param thumbName:图片名称
     * @param thumbFilename:图片保存路径
     * @param width:图片宽
     * @param height:图片高
     * @param hour:指定时
     * @param min:指定分
     * @param sec:指定秒
     * @throws IOException
     * @throws InterruptedException
     */
    public String getVideoPhoto(String videoFilename, String thumbName, int width, int height, int hour, int min,
                                float sec) throws IOException, InterruptedException {
        String pictureUrl = "";
        // 图片存放地址
        String thumbFilename = TMP_PATH + thumbName + ".jpg";
        logger.info("图片存放地址" + thumbFilename);

        String command = FFMPEG_PATH + "ffmpeg -i " + videoFilename + " -y -f  image2  -ss " + hour + ":" + min + ":"
                + sec + " -vframes 1 " + thumbFilename;
        logger.info("获取视频第一帧命令: " + command);
        Process process = Runtime.getRuntime().exec(command);
        process.waitFor();

        File ff = new File(thumbFilename);
        FileInputStream fs = new FileInputStream(ff);
        byte[] bytes = new byte[fs.available()];
        // 将文件内容写入字节数组，提供测试的case
        fs.read(bytes);
        try {
            pictureUrl = FastDFSClient.uploadFile(bytes, null);
            fs.close();
            File file = new File(thumbFilename);
            file.delete();
        } catch (Exception e) {
            logger.error("图片文件上传失败,图片路径：" + thumbFilename);
            e.printStackTrace();
        }
        return pictureUrl;
    }

    /**
     * 上传图片
     *
     * @param thumbFilename
     * @return
     * @throws IOException
     */
    public String uploadFiles(String thumbFilename) throws IOException {
        String pictureUrl = "";
        File ff = new File(thumbFilename);
        FileInputStream fs = new FileInputStream(ff);
        byte[] bytes = new byte[fs.available()];
        // 将文件内容写入字节数组，提供测试的case
        fs.read(bytes);
        try {
            pictureUrl = FastDFSClient.uploadFile(bytes, null);
            fs.close();
            File file = new File(thumbFilename);
            file.delete();
        } catch (Exception e) {
            logger.error("图片文件上传失败,图片路径：" + thumbFilename);
            e.printStackTrace();
        }
        return pictureUrl;

    }

    public static void main(String[] args) {
        try {
            String url = new FFMpegMusicUtil().getThumb("D:\\image\\aa.mp4", "33", 848, 480, 00, 00, 01);

            System.out.println("url=========" + url);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

    }

}
